import pygame
from math import sin

class Entity(pygame.sprite.Sprite):
	def __init__(self,groups):
		super().__init__(groups)

		#初始化帧索引
		self.frame_index = 0
		#设置动画播放速度
		self.animation_speed = 0.15
		#创建一个零向量，默认为：（x=0, y=0）
		self.direction = pygame.math.Vector2()
		
	def move(self,speed):
		#码检查 self.direction 向量的模是否不为 0（也就是向量不为（0, 0）时，说明有方向键按下）
		if self.direction.magnitude() != 0:
			self.direction = self.direction.normalize()

		self.hitbox.x += self.direction.x * speed
		self.collision('horizontal')
		self.hitbox.y += self.direction.y * speed
		self.collision('vertical')
		# 更新 self.rect 的位置，使其与 self.hitbox 的位置相同
		self.rect.center = self.hitbox.center

	def collision(self,direction):
		if direction == 'horizontal':
			for sprite in self.obstacle_sprites:
				if sprite.rect.colliderect(self.hitbox):
					if self.direction.x > 0: 
						self.hitbox.right = sprite.rect.left
					if self.direction.x < 0: 
						self.hitbox.left = sprite.rect.right

		if direction == 'vertical':
			for sprite in self.obstacle_sprites:
				if sprite.rect.colliderect(self.hitbox):
					if self.direction.y > 0: 
						self.hitbox.bottom = sprite.rect.top
					if self.direction.y < 0: 
						self.hitbox.top = sprite.rect.bottom


	def wave_value(self):
		value = sin(pygame.time.get_ticks())
		if value >= 0: 
			return 255
		else: 
			return 0